<template>
  <j-modal
    :title="showSaveBtn? '新增交付信息':'编辑交付信息'"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :model="model" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
        <a-row>
          <h2>交车信息：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="合同编号">
              <a-auto-complete
                placeholder="请输入合同编号"
                v-decorator="['contractNo', { rules: [{ required: true, message: '请输入合同编号' }] }]"

              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="订单号">
              <a-input
                placeholder="请输入销售合同对应的订单号"
                v-decorator="['orderNumber', { rules: [{ required: true, message: '请输入订单号' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="交车地点">
              <a-input
                placeholder="请输入交车地点"
                v-decorator="['deliveryAddr', { rules: [{ required: true, message: '请输入交车地点' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="交车时间">
              <a-date-picker
                placeholder="请选择交车时间"
                style="width: 100%"
                :showTime="true"
                format="yyyy-MM-DD HH:mm:ss"
                v-decorator="['deliveryTime', { rules: [{ required: true, message: '请选择交车时间' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <h2>车辆信息</h2>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="车架号(vin码)">
              <a-input
                placeholder="请输入车架号"
                v-decorator="['carVin', { rules: [{ required: true, message: '请输入车架号' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="发动机号">
              <a-input
                placeholder="请输入发动机号"
                v-decorator="['engineNumber', { rules: [{ required: true, message: '请输入发动机号' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="品牌及规格型号">
              <a-input
                placeholder="请输入品牌及规格型号"
                v-decorator="['carBrandNumber', { rules: [{ required: false, message: '请输入品牌及规格型号' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="动力蓄电池组编号">
              <a-input
                placeholder="请输入动力蓄电池组编号"
                v-decorator="['batteryNumber', { rules: [{ required: false, message: '请输入动力蓄电池组编号' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="外饰颜色">
              <a-input
                placeholder="请输入外饰颜色"
                v-decorator="['carColor', { rules: [{ required: true, message: '请输入外饰颜色' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="内饰颜色">
              <a-input
                placeholder="请输入内饰颜色"
                v-decorator="['interiorColor', { rules: [{ required: true, message: '请输入内饰颜色' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <h2>交易信息("机动车销售统一发票"信息)</h2>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="开票日期">
              <a-date-picker
                placeholder="请选择开票日期"
                style="width: 100%"
                :showTime="true"
                format="YYYY-MM-DD HH:mm:ss"
                v-decorator="['invoiceTime', { rules: [{ required: true, message: '请输入开票日期' }] }]"
              />
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="发票代码">
              <a-input
                placeholder="请输入发票代码"
                v-decorator="['invoiceCode', { rules: [{ required: true, message: '请输入发票代码' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="发票号码">
              <a-input
                placeholder="请输入发票号码"
                v-decorator="['invoiceNumber', { rules: [{ required: true, message: '请输入发票号码' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="不含税价">
              <a-input-number
                placeholder="请输入不含税价"
                style="width: 100%"
                v-decorator="['excludingTaxPrice', { rules: [{ required: true, message: '请输入不含税价' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="价税合计">
              <a-input-number
                placeholder="请输入价税合计"
                style="width: 100%"
                v-decorator="['invoicePrice', { rules: [{ required: true, message: '请输入价税合计' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="总实收">
              <a-input-number
                placeholder="请输入总实收"
                style="width: 100%"
                v-decorator="['receivedamount', { rules: [{ required: true, message: '请输入总实收' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <h2>交付方信息</h2>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="企业名称">
              <a-input
                placeholder="请输入企业名称"
                style="width: 100%"
                v-decorator="['enterpriseName', { rules: [{ required: false, message: '请输入企业名称' }] }]"
              />
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="交付专员">
              <a-auto-complete
                placeholder="请输入交付专员"
                style="width: 100%"
                :data-source="saleSource"
                @select="saleSelect"
                @change="saleChange"
                v-decorator="['salesName', { rules: [{ required: true, message: '请输入交付专员' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="交付专员联系电话">
              <a-auto-complete
                placeholder="请输入交付专员联系电话"
                v-decorator="['salesPhone', { rules: [{ required: true, message: '请输入交付专员联系电话' },
                {pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,message:'手机号格式不正确'}] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <h2>接收方信息</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="接收方姓名">
              <a-input
                placeholder="请输入接收方姓名"
                v-decorator="['buyerName', { rules: [{ required: true, message: '请输入接收方姓名' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="接收方手机号码">
              <a-input
                placeholder="请输入接收方手机号码"
                v-decorator="['buyerPhone', { rules: [{ required: true, message: '请输入接收方手机号码' },
                {pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,message:'手机号格式不正确'}] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="接收方证件类型">
              <a-select
                v-decorator="['pinType', { rules: [{ required: true, message: '请选择接收方证件类型' }] }]"
                placeholder="请选择接收方证件类型"
              >
                <a-select-option value="1">身份证</a-select-option>
                <a-select-option value="2">护照</a-select-option>
                <a-select-option value="3">士兵证军官证</a-select-option>
                <a-select-option value="4">港澳居民居住证</a-select-option>
                <a-select-option value="5">港澳居民来往内地通行证</a-select-option>
                <a-select-option value="6">台湾居民居住证</a-select-option>
                <a-select-option value="7">台湾居民来往大陆通行证</a-select-option>
                <a-select-option value="8">外国人永久居留身份证</a-select-option>
                <a-select-option value="9">其他有效身份证明</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="接收方证件号码">
              <a-input
                :maxLength="18"
                placeholder="请输入接收方证件号码"
                v-decorator="['pinNumber', { rules: [{validator: this.checkValue}] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <h2>交付清单</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="交付清单">
              <a-textarea
                style="width: 200%"
                placeholder="请输入交付清单"
                v-decorator="['deliverContents', { rules: [{ required: true, message: '请输入交付清单' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </a-spin>
    <a-button v-if="showSaveBtn" type="primary" @click="saveDraft">暂存</a-button>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'NewDeliveryModal',
  data() {
    return {
      title: '交付信息',
      visible: false,
      model: {},
      saleSource: [],
      SaleInfosLike: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      orderId:'',
      showSaveBtn:false,
      url: {
        add: '/cxm/cxmDeliverManager/add',
        edit: '/cxm/cxmDeliverManager/edit',
        saveDraft: 'cxm/cxmCommonBusiness/saveDraft',
        getDraft: 'cxm/cxmCommonBusiness/getDraft',
        getSaleInfosLike: 'cxm/cxmSalesInfo/getSaleInfosLike'
      },
    }
  },
  methods: {
    //验证身份证号
    checkValue(rule, value, callback) {
      if(value.length > 0) {
        const pinType = this.form.getFieldValue('pinType')
        const regExp = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/
        if(pinType == 1) {
          if(new RegExp(regExp).test(value)) {
            callback()
          }else {
            callback(new Error('身份证号格式不正确'))
          }
        }
      }else {
        callback(new Error('请输入接收方证件号码'))
      }
    },
    saleSelect(value) {
      console.log('saleSelect', value);
      for (let i = 0; i < this.SaleInfosLike.length; i++) {
        if (this.SaleInfosLike[i].salesName == value) {
          this.form.setFieldsValue({
            salesPhone: this.SaleInfosLike[i].salesPhone
          })
        }
      }
    },
    saleChange(value) {
      console.log('methods => saleChange => value ', value)
      console.log(this.form.getFieldValue("salesName"))
      setTimeout(() => {
        let httpurl = this.url.getSaleInfosLike
        let params = {
          salesName: this.form.getFieldValue("salesName")
        }
        getAction(httpurl, params).then((res) => {
          if (res.success) {
            this.SaleInfosLike = res.result
            this.saleSource = [];
            for (let i = 0; i < res.result.length; i++) {
              this.saleSource.push(res.result[i].salesName)
              if (i > 8) {
                break;
              }
            }
          }
        })
      }, 100);
    },
    add(id,record) {
      console.log('methods => add => record ', record)
      this.visible = true
      this.orderId = id
      this.showSaveBtn = true
      delete record.id
      delete record.deliveryTime
      const contractData = record
      let params = {
        bType: "deliver"+id
      };
      getAction(this.url.getDraft, params).then((res) => {
        if (res.success) {
          if(res.result) {
            this.edit(JSON.parse(res.result))
          } else {
            this.edit(contractData)
          }
        } else {
          this.edit({})
        }
      })
    },
    edit(record) {
      console.log(record);
      this.form.resetFields()
      this.model = {}
      this.model = Object.assign({}, record)
      console.log(this.model);
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue({
          batteryNumber: this.model.batteryNumber,
          buyerName: this.model.buyerName,
          buyerPhone: this.model.buyerPhone,
          carBrandNumber: this.model.carBrandNumber,
          carColor: this.model.carColor,
          carVin: this.model.carVin,
          contractNo: this.model.contractNo,
          deliverContents: this.model.deliverContents,
          deliveryAddr: this.model.deliveryAddr,
          deliveryTime: this.model.deliveryTime ? moment(this.model.deliveryTime) : null,        //时间格式化
          engineNumber: this.model.engineNumber,
          enterpriseName: this.model.enterpriseName,
          excludingTaxPrice:this.model.excludingTaxPrice,
          receivedamount:this.model.receivedamount,
          interiorColor: this.model.interiorColor,
          orderNumber: this.model.orderNumber,
          pinNumber: this.model.pinNumber,
          pinType: this.model.pinType,
          salesName: this.model.salesName,
          salesPhone: this.model.salesPhone,
          invoiceCode: this.model.invoiceCode,
          invoiceNumber: this.model.invoiceNumber,
          invoicePrice: this.model.invoicePrice,
          invoiceTime: this.model.invoiceTime ? moment(this.model.invoiceTime) : null
        })
      })

    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let url = ''
          let method = ''

          if (!this.model.id) {
            url += this.url.add
            method = 'post'
          } else {
            url += this.url.edit
            method = 'put'
          }
          let formData = Object.assign({},this.model, values)
          //时间格式化
          formData.deliveryTime = formData.deliveryTime ? formData.deliveryTime.format('YYYY-MM-DD HH:mm:ss') : null
          formData.invoiceTime = formData.invoiceTime ? formData.invoiceTime.format('YYYY-MM-DD HH:mm:ss') : null

          httpAction(url, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.close()
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.visible = false
      this.orderId = ''
      this.showSaveBtn = false
      this.model = {}
      this.form.resetFields()
    },
    saveDraft() {
      const that = this
      this.form.validateFields((err, values) => {
        let formData = Object.assign({}, values)
        //时间格式化
        formData.deliveryTime = formData.deliveryTime ? formData.deliveryTime.format('YYYY-MM-DD HH:mm:ss') : null
        formData.invoiceTime = formData.invoiceTime ? formData.invoiceTime.format('YYYY-MM-DD HH:mm:ss') : null
        let params = {
          btype:"deliver"+this.orderId,
          content:JSON.stringify(formData)
        }
        httpAction( this.url.saveDraft, params, 'post')
          .then((res) => {
            if (res.success) {
              that.$message.success(res.message)
            } else {
              that.$message.warning(res.message)
            }
          })
          .finally(() => {
            that.confirmLoading = false
            that.close()
          })
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>